<?php

/**
 * Description of model_posts
 *
 * @author Steffen Bilde
 */
class model_posts extends CI_Model
{
    function  __construct()
    {
        parent::__construct();
    }

        //Gets id,title,created ad user_id for all 'post's up to 25.
    	function list_posts($limit=25)
        {
            $data = array();
            $this->db->select('id,title,created,user_id');
            $this->db->limit($limit);
            $Q = $this->db->get('posts');
            if ($Q->num_rows() > 0)
            {
                foreach ($Q->result() as $row)
                {
                   $data[$row->id] = $row;
                }
            }

            $Q->free_result();
            return $data;
	}

        //Gets a all post by a given user ($list_of_ids) up to 50.
        function list_user_posts($list_of_ids,$limit=50)
        {
            $data = array();          
            $this->db->select('id,title,created');
            $this->db->where_in("user_id",$list_of_ids);
            $this->db->order_by('created','desc');
            $this->db->limit($limit);         
            $Q = $this->db->get("posts");
            if ($Q->num_rows() > 0)
            {
                foreach ($Q->result() as $row)
                {
                    $data[$row->id] = $row;
                }
            }
            $Q->free_result();
            return $data;
	}

        //Gets post by $id
	function get_post($id){
		$data = array();
		$this->db->where('id',$id);
		$this->db->limit(1);
		$Q = $this->db->get('posts');
		if ($Q->num_rows() > 0){
			$data = $Q->row();
		}

		$Q->free_result();
		return $data;
	}

        //get post-id,title,created and user_id by $id.
	function get_post_short($id){
		$data = array();
		$this->db->select('id,title,created,user_id');
		$this->db->where('id',$id);
		$this->db->limit(1);
		$Q = $this->db->get('posts');
		if ($Q->num_rows() > 0){
			$data = $Q->row();
		}

		$Q->free_result();
		return $data;
	}

        //Create a post in 'post'-table by 'logged_in_user'
	function add_post(){
		$userid = $this->session->userdata('id');
		$now = date("Y-m-d h:i:s");
		$data = array(
                        'title' => $this->input->post('title'),
                        'body' => $this->input->post('body'),
			'user_id' => $userid,
			'created' => $now
		);

		$this->db->insert("posts",$data);
		
		return $this->db->insert_id();
	}

        //Deletes a post by $id
	function delete_post($id){
		$this->db->limit(1);
		$this->db->where('id', $id);
		$this->db->delete('posts');
	}



}
?>
